package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
//        查询redis中店铺类型数据
        List<String> types = stringRedisTemplate.opsForList().range("cache:type:" + RedisConstants.SHOP_GEO_KEY, 0, -1L);
        List<ShopType> shopTypes = new ArrayList<>();
        for (String type : types) {
//            TODO String咋勾八转不了实体类对象了？！
            ShopType shopType = JSONUtil.toBean(type, ShopType.class);
            shopTypes.add(shopType);
        }/*转为shopType类型*/
        if (shopTypes != null && shopTypes.size() > 0) {
//            直接返回
            return shopTypes;
        }
//        查询该表中所有数据
        List<ShopType> typeList = query().orderByAsc("sort").list();
//        数据库没有就返回错误
        if (typeList == null || typeList.isEmpty()) {
            return null;
        }
//        数据库有就写入redis，返回结果
        String cacheKey = "cache:type:" + RedisConstants.SHOP_GEO_KEY;
//        遍历集合逐个写入redis
        typeList.forEach(type -> stringRedisTemplate.opsForList().rightPush(cacheKey, JSONUtil.toJsonStr(type)));
        /*设置3分钟有效时间*/
        stringRedisTemplate.expire(cacheKey, 3, TimeUnit.MINUTES);
        return typeList;
    }
}
